<template>
  <view class="search-filter">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <uni-search-bar 
        v-model="searchForm.keyword" 
        placeholder="搜索活动名称"
        @confirm="handleSearch"
        @clear="handleClearSearch"
        :focus="false"
        :show-action="false"
      />
      <button class="filter-btn" @click="toggleFilter">
        <uni-icons type="tune" size="20" />
        <text>筛选</text>
      </button>
    </view>

    <!-- 筛选面板 -->
    <uni-transition 
      :show="showFilter" 
      mode-class="slide-top"
      :duration="300"
    >
      <view class="filter-panel">
        <!-- 活动状态 -->
        <view class="filter-section">
          <text class="filter-label">活动状态</text>
          <scroll-view class="filter-scroll" scroll-x>
            <view class="filter-options">
              <view 
                class="filter-option"
                :class="{ active: searchForm.status === item.value }"
                v-for="item in statusOptions"
                :key="item.value"
                @click="handleStatusChange(item.value)"
              >
                <text class="option-text">{{ item.label }}</text>
              </view>
            </view>
          </scroll-view>
        </view>

        <!-- 价格范围 -->
        <view class="filter-section">
          <text class="filter-label">价格范围</text>
          <view class="price-range">
            <uni-easyinput 
              v-model="searchForm.minPrice" 
              type="number"
              placeholder="最低价"
              :inputBorder="false"
            />
            <text class="price-separator">-</text>
            <uni-easyinput 
              v-model="searchForm.maxPrice" 
              type="number"
              placeholder="最高价"
              :inputBorder="false"
            />
          </view>
        </view>

        <!-- 时间范围 -->
        <view class="filter-section">
          <text class="filter-label">活动时间</text>
          <view class="time-range">
            <uni-datetime-picker 
              v-model="searchForm.startTime"
              type="date"
              placeholder="开始日期"
              @change="handleStartTimeChange"
            />
            <text class="time-separator">至</text>
            <uni-datetime-picker 
              v-model="searchForm.endTime"
              type="date"
              placeholder="结束日期"
              @change="handleEndTimeChange"
            />
          </view>
        </view>

        <!-- 排序方式 -->
        <view class="filter-section">
          <text class="filter-label">排序方式</text>
          <uni-data-checkbox 
            v-model="searchForm.sortBy"
            :localdata="sortOptions"
          />
        </view>

        <!-- 操作按钮 -->
        <view class="filter-actions">
          <button class="action-btn secondary" @click="handleReset">
            <text>重置</text>
          </button>
          <button class="action-btn primary" @click="handleConfirm">
            <text>确定</text>
          </button>
        </view>
      </view>
    </uni-transition>

    <!-- 已选筛选条件 -->
    <view class="active-filters" v-if="hasActiveFilters">
      <scroll-view class="filters-scroll" scroll-x>
        <view class="filters-list">
          <view 
            v-if="searchForm.status && searchForm.status !== 'all'"
            class="filter-tag"
            @click="clearStatusFilter"
          >
            <text>{{ getStatusLabel(searchForm.status) }}</text>
            <uni-icons type="close" size="12" />
          </view>
          
          <view 
            v-if="searchForm.minPrice || searchForm.maxPrice"
            class="filter-tag"
            @click="clearPriceFilter"
          >
            <text>价格: {{ formatPriceRange() }}</text>
            <uni-icons type="close" size="12" />
          </view>
          
          <view 
            v-if="searchForm.startTime || searchForm.endTime"
            class="filter-tag"
            @click="clearTimeFilter"
          >
            <text>时间: {{ formatTimeRange() }}</text>
            <uni-icons type="close" size="12" />
          </view>
        </view>
      </scroll-view>
      
      <button class="clear-all-btn" @click="handleClearAll">
        <text>清空</text>
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';

// 搜索表单数据
const searchForm = reactive({
  keyword: '',
  status: 'all',
  minPrice: '',
  maxPrice: '',
  startTime: '',
  endTime: '',
  sortBy: 'created_at_desc',
});

// 筛选面板显示状态
const showFilter = ref(false);

// 状态选项
const statusOptions = [
  { label: '全部', value: 'all' },
  { label: '进行中', value: 'active' },
  { label: '未开始', value: 'pending' },
  { label: '已结束', value: 'ended' },
  { label: '已禁用', value: 'disabled' },
];

// 排序选项
const sortOptions = [
  { value: 'created_at_desc', text: '创建时间(新到旧)' },
  { value: 'created_at_asc', text: '创建时间(旧到新)' },
  { value: 'start_time_desc', text: '开始时间(晚到早)' },
  { value: 'start_time_asc', text: '开始时间(早到晚)' },
  { value: 'price_desc', text: '价格(高到低)' },
  { value: 'price_asc', text: '价格(低到高)' },
];

// Emits
const emit = defineEmits<{
  search: [params: any];
  reset: [];
}>();

// 计算属性
const hasActiveFilters = computed(() => {
  return searchForm.keyword || 
         (searchForm.status && searchForm.status !== 'all') ||
         searchForm.minPrice || 
         searchForm.maxPrice ||
         searchForm.startTime || 
         searchForm.endTime;
});

// 切换筛选面板
const toggleFilter = () => {
  showFilter.value = !showFilter.value;
};

// 处理搜索
const handleSearch = () => {
  emitSearchParams();
};

// 清除搜索
const handleClearSearch = () => {
  searchForm.keyword = '';
  emitSearchParams();
};

// 处理状态变化
const handleStatusChange = (status: string) => {
  searchForm.status = status;
};

// 处理开始时间变化
const handleStartTimeChange = (value: string) => {
  searchForm.startTime = value;
};

// 处理结束时间变化
const handleEndTimeChange = (value: string) => {
  searchForm.endTime = value;
};

// 处理重置
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: 'all',
    minPrice: '',
    maxPrice: '',
    startTime: '',
    endTime: '',
    sortBy: 'created_at_desc',
  });
  emit('reset');
};

// 处理确定
const handleConfirm = () => {
  showFilter.value = false;
  emitSearchParams();
};

// 清空所有筛选
const handleClearAll = () => {
  handleReset();
};

// 清除状态筛选
const clearStatusFilter = () => {
  searchForm.status = 'all';
  emitSearchParams();
};

// 清除价格筛选
const clearPriceFilter = () => {
  searchForm.minPrice = '';
  searchForm.maxPrice = '';
  emitSearchParams();
};

// 清除时间筛选
const clearTimeFilter = () => {
  searchForm.startTime = '';
  searchForm.endTime = '';
  emitSearchParams();
};

// 获取状态标签
const getStatusLabel = (status: string) => {
  const option = statusOptions.find(item => item.value === status);
  return option?.label || '';
};

// 格式化价格范围
const formatPriceRange = () => {
  const min = searchForm.minPrice;
  const max = searchForm.maxPrice;
  if (min && max) return `¥${min}-¥${max}`;
  if (min) return `≥¥${min}`;
  if (max) return `≤¥${max}`;
  return '';
};

// 格式化时间范围
const formatTimeRange = () => {
  const start = searchForm.startTime;
  const end = searchForm.endTime;
  if (start && end) return `${start}至${end}`;
  if (start) return `从${start}`;
  if (end) return `到${end}`;
  return '';
};

// 发送搜索参数
const emitSearchParams = () => {
  const params: any = {};
  
  if (searchForm.keyword) {
    params.keyword = searchForm.keyword;
  }
  
  if (searchForm.status && searchForm.status !== 'all') {
    params.status = searchForm.status;
  }
  
  if (searchForm.minPrice) {
    params.minPrice = parseFloat(searchForm.minPrice) * 100; // 转换为分
  }
  
  if (searchForm.maxPrice) {
    params.maxPrice = parseFloat(searchForm.maxPrice) * 100; // 转换为分
  }
  
  if (searchForm.startTime) {
    params.startTime = new Date(searchForm.startTime).getTime() / 1000;
  }
  
  if (searchForm.endTime) {
    params.endTime = new Date(searchForm.endTime + ' 23:59:59').getTime() / 1000;
  }
  
  if (searchForm.sortBy) {
    const [field, order] = searchForm.sortBy.split('_');
    params.sortField = field;
    params.sortOrder = order;
  }
  
  emit('search', params);
};

// 暴露方法给父组件
defineExpose({
  reset: handleReset,
});
</script>

<style lang="scss" scoped>
.search-filter {
  background: #fff;
  border-bottom: 1rpx solid #f0f0f0;
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 24rpx 32rpx;
  gap: 16rpx;
  
  .uni-searchbar {
    flex: 1;
  }
  
  .filter-btn {
    display: flex;
    align-items: center;
    gap: 8rpx;
    padding: 16rpx 24rpx;
    background: #f5f5f5;
    border: none;
    border-radius: 20rpx;
    font-size: 26rpx;
    color: #666;
    
    &:active {
      background: #e6e6e6;
    }
  }
}

.filter-panel {
  padding: 32rpx;
  border-top: 1rpx solid #f0f0f0;
  background: #fafafa;
}

.filter-section {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .filter-label {
    display: block;
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 16rpx;
  }
}

.filter-scroll {
  white-space: nowrap;
  
  .filter-options {
    display: flex;
    gap: 16rpx;
    
    .filter-option {
      flex-shrink: 0;
      padding: 12rpx 24rpx;
      background: #fff;
      border: 1rpx solid #e6e6e6;
      border-radius: 20rpx;
      transition: all 0.3s ease;
      
      &.active {
        background: #1890FF;
        border-color: #1890FF;
        
        .option-text {
          color: #fff;
        }
      }
      
      .option-text {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.price-range, .time-range {
  display: flex;
  align-items: center;
  gap: 16rpx;
  
  .uni-easyinput {
    flex: 1;
    background: #fff;
    border-radius: 8rpx;
  }
  
  .price-separator, .time-separator {
    font-size: 24rpx;
    color: #999;
  }
}

.filter-actions {
  display: flex;
  gap: 24rpx;
  margin-top: 32rpx;
  
  .action-btn {
    flex: 1;
    padding: 24rpx;
    border-radius: 12rpx;
    font-size: 28rpx;
    border: none;
    
    &.secondary {
      background: #fff;
      color: #666;
      border: 1rpx solid #e6e6e6;
    }
    
    &.primary {
      background: #1890FF;
      color: #fff;
    }
    
    &:active {
      opacity: 0.8;
    }
  }
}

.active-filters {
  display: flex;
  align-items: center;
  padding: 16rpx 32rpx;
  background: #f9f9f9;
  border-top: 1rpx solid #f0f0f0;
  
  .filters-scroll {
    flex: 1;
    white-space: nowrap;
    
    .filters-list {
      display: flex;
      gap: 12rpx;
      
      .filter-tag {
        display: flex;
        align-items: center;
        gap: 8rpx;
        padding: 8rpx 16rpx;
        background: #1890FF;
        color: #fff;
        border-radius: 16rpx;
        font-size: 22rpx;
        flex-shrink: 0;
        
        &:active {
          opacity: 0.8;
        }
      }
    }
  }
  
  .clear-all-btn {
    margin-left: 16rpx;
    padding: 8rpx 16rpx;
    background: #FF4D4F;
    color: #fff;
    border: none;
    border-radius: 16rpx;
    font-size: 22rpx;
    
    &:active {
      opacity: 0.8;
    }
  }
}
</style>